package com.hmall.gateway.filter;

import com.github.xiaoymin.knife4j.core.oauth2.OAuth2Properties;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    private final JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径
        String path = exchange.getRequest().getURI().getPath();

        //如果当前请求路径在白名单中，则直接放行
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path)) {
                return chain.filter(exchange);
            }
        }
        //2.获取本次请求鞋底啊的令牌，黑马商城项目，是在请求头中有一个Authorization，值是令牌
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token == null || "".equals(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //3.校验解析令牌
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            log.error("解析令牌失败，请重新登录", e);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //4.将当前用户的id添加到请求头上，从exchange里得到的Request和response默认是不能修改的，需要执行mutate（）然后才能修改
        exchange.getRequest().mutate().header("user-info",userId.toString());
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
